﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DoubanApiLib.OAuth;
using System.Web;

namespace DoubanApiLib.Base
{
    /// <summary>
    /// 工具类
    /// </summary>
    public sealed class Until
    {
        public static Dictionary<string, string> ParseResponse(string parameters)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();

            if (!string.IsNullOrEmpty(parameters))
            {
                string[] p = parameters.Split('&');
                foreach (string s in p)
                    if (!string.IsNullOrEmpty(s))
                        if (s.IndexOf('=') > -1)
                        {
                            string[] temp = s.Split('=');
                            result.Add(temp[0], temp[1]);
                        }
                        else result.Add(s, string.Empty);
            }

            return result;
        }

        /// <summary>
        /// 创建授权Header
        /// </summary>
        /// <param name="url"></param>
        /// <param name="accessToken"></param>
        /// <param name="accessTokenSecret"></param>
        /// <returns></returns>
        public static string CreateOauthHeader(string url, string accessToken, string accessTokenSecret)
        {
            Uri uri = GetBaseUri(url);

            OAuthBase oAuth = OAuthWork.oAuth;
            string nonce = oAuth.GenerateNonce();
            string timeStamp = oAuth.GenerateTimeStamp();
            string normalizeUrl, normalizedRequestParameters;

            // 签名
            string sig = oAuth.GenerateSignature(
                uri,
                Runtime.SystemParam.API_KEY,
                Runtime.SystemParam.API_KEY_SECRET,
                accessToken,
                accessTokenSecret,
                "POST",
                timeStamp,
                nonce,
                OAuthBase.SignatureTypes.HMACSHA1,
                out normalizeUrl,
                out normalizedRequestParameters);
            sig = HttpUtility.UrlEncode(sig);

            //构造OAuth头部
            StringBuilder oauthHeader = new StringBuilder();
            oauthHeader.AppendFormat("OAuth realm=\"\", oauth_consumer_key={0}, ", Runtime.SystemParam.API_KEY);
            oauthHeader.AppendFormat("oauth_nonce={0}, ", nonce);
            oauthHeader.AppendFormat("oauth_timestamp={0}, ", timeStamp);
            oauthHeader.AppendFormat("oauth_signature_method={0}, ", "HMAC-SHA1");
            oauthHeader.AppendFormat("oauth_version={0}, ", "1.0");
            oauthHeader.AppendFormat("oauth_signature={0}, ", sig);
            oauthHeader.AppendFormat("oauth_token={0}", accessToken);

            return oauthHeader.ToString();
        }


        public static Uri GetBaseUri(string urlstr)
        {
            Uri url = new Uri(urlstr);
            string normalizedUrl = string.Format("{0}://{1}", url.Scheme, url.Host);
            if (!((url.Scheme == "http" && url.Port == 80) || (url.Scheme == "https" && url.Port == 443)))
            {
                normalizedUrl += ":" + url.Port;
            }
            normalizedUrl += url.AbsolutePath;

            return new Uri(normalizedUrl);
        }
    }
}
